package cn.q3c.web.tool.dao;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.springframework.stereotype.Service;

import com.googlecode.ehcache.annotations.Cacheable;

import cn.q3c.web.tool.object.Url;

@Service
public class UrlDAO extends BaseDAO{

	@Cacheable(cacheName="departCache") 
	public Url getUrl(String url) throws SQLException {

		Connection conn = dataSource.getConnection();

		String sql = "select * from t_urls where url=?";

		Url result = null;
		try {

			Object[] objs = new Object[] { url };

			result = (Url) this.query(conn, sql,
					new BeanHandler<Url>(Url.class), objs);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.close(conn);
		}

		return result;
	}

	public long addUrl(Url url) throws SQLException {

		Connection conn = null;

		long id = -1;
		String sql = "insert into t_urls(`url`,`trueurl`,`cdate`,`udate`) values(?,?,now(),now())";

		try {

			conn = dataSource.getConnection();

			Object[] objs = new Object[] { 
					url.getUrl(),
					url.getTrueurl()
					};
			this.update(conn, sql, objs);

			id = getLastInsertID(conn);

			DbUtils.close(conn);
		} catch (SQLException e) {
			DbUtils.close(conn);
			e.printStackTrace();
		}

		return id;
	}
	
	
	public void updateUrlDate(int nid) throws SQLException {

		Connection conn = null;
		String sql = "update t_urls set udate=now() where nid=?";

		try {

			conn = dataSource.getConnection();

			Object[] objs = new Object[] { 
					nid};
			this.update(conn, sql, objs);

			DbUtils.close(conn);
		} catch (SQLException e) {
			DbUtils.close(conn);
			e.printStackTrace();
		}
	}
}
